package com.lwx.es;

import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;

import com.lwx.es.model.ProductEsModel;

public class EsManager {
	private Client client;
	private String indexName = "portal";
	private String indexType = "product";

	public void init() throws IOException {
		Settings settings = ImmutableSettings.settingsBuilder()
				.put("cluster.name", "myes")
				.put("client.transport.sniff", true).build();

		client = new TransportClient(settings)
			.addTransportAddress(new InetSocketTransportAddress("192.168.56.201", 9300));
		String content = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("com/lwx/es/es-portal-product-mapping.json"));
		
        PutMappingRequest mappingRequest = Requests.putMappingRequest(indexName).type(indexType).source(content);  
        client.admin().indices().putMapping(mappingRequest).actionGet();  
	}

	public void index(ProductEsModel model) throws ElasticsearchException, IOException {
		IndexResponse response = client
				.prepareIndex(indexName, indexType, model.getDocId())
				.setSource(model.getJson()).execute().actionGet();
	}
	
	public SearchResponse search(QueryBuilder queryBuilder){
		SearchRequestBuilder requestBuilder = client.prepareSearch(indexName).setTypes(indexType).setQuery(queryBuilder).setFrom(0).setSize(10);
		SearchResponse response = requestBuilder.execute().actionGet();
		return response;
	}
}
